import {defineStore} from "pinia";
// @ts-ignore
import {ajax, requestCache} from "@/js/api_tool.js";
// @ts-ignore
import {cacheGet, cacheSet} from "@/store/pluginCache.js";

interface TypeMenuItem {
    id: number;
    parent_id: number;
    name: string;
    title: string;
    head_img: string;
    path: string;
    param: string;
    url: string;
    right: string;
    unique: string;
    badge: string;
    children?: TypeMenuItem[];
}

export const use_menu_list = defineStore('menu_list', {
    state: ():{
        list: TypeMenuItem[]
    } => {
        return {
            list: []
        }
    },
    actions: {
        /**通过请求接口，获取数据后合并，来刷新数据
         */
        async refresh(){
            try {
                let res = await ajax({url: '/admin/index/menu', showMessage: ajax.SHOW_MESSAGE_NONE});
                let data = {list: res.data}
                let old = cacheGet(this.$id);
                const old_json = JSON.stringify(old);
                const data_json = JSON.stringify(data);
                if (old_json !== data_json){
                    console.log(`refresh ${this.$id} ok`)
                    this.$patch(data);
                    cacheSet(this.$id, data);
                }
            } catch (e:any) {
                console.log(`refresh fail: ${e.message || e}`)
            }
        },
    }
})
